<?php
namespace App\Logic;

use Common\Model\VersionModel;

class VersionLogic extends VersionModel
{
	protected function _initialize()
	{
		parent::_initialize();
	}

	public function checkVersion($query = array())
	{
		$field = array(
			'version_status'=>'status',
			'version_name'=>'name',
			'version_release'=>'version',
			'version_code'=>'code',
			'version_download'=>'url',
			'version_message'=>'message',
			'version_description'=>'description',
			'version_platform'=>'platform',
			'version_key' => 'key',
			'version_notice'=>'notice'
		);
			
		$where = array(
				'version_type' 		=> $query['type'],
				'version_platform'	=> $query['platform'],
				'version_code'		=> $query['code'],
		);
		
		$ret = array();
		$ret = $this->field($field)->where($where)->getItem();
		
		if($ret === false)
		{
			$this->error = '查询异常';
			return false;
		}
		
		if( empty($ret) === true )
		{
			$ret['key'] = empty($ret['key']) === false ? $ret['key'] : '72969e04baa8b6e43fae34e1969d56a6';
			$ret['status'] = 0;
			$ret['message'] = '此版本已停用，请下载最新版本';
		}
		
		return $ret;
	}
	
	public function checkRequire($required = array(),$query = array())
	{
		$diff = array_diff($required,array_keys($query));
	
		if( empty($diff) === false )
		{
			foreach ($diff as $row)
			{
				$this->error .= $row . '不能为空,';
			}
	
			$this->error = trim($this->error,',');
	
			return false;
		}
		return true;
	}
	
	public function checkSign($data = array())
	{
		$clientSign = $data['sign'];
	
		$sign = $this->getSigntrue($data);
		
		return $clientSign === $sign;
	}
	
	public function getSigntrue(&$data = array())
	{
		ksort($data);
		
		$ckey = $data['key'];
		
		unset($data['sign'],$data['key']);
		
		$query = '';
		
		foreach ($data as $key => $item)
		{
			$query .= "&{$key}={$item}";
		}
		
		$query = trim($query,'&');
		
		$query .= $ckey;

		return md5($query);
	}
}